package com.ulook.lookplanet.service;

import com.ulook.lookplanet.bean.*;
import com.ulook.lookplanet.common.ComPath;
import com.ulook.lookplanet.mapper.ManageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

/**
 * 描述：
 *
 * @author L1998
 * @date 2021/5/13
 */
@Service
public class ManageService {

    @Autowired
    private ManageMapper mapper;

    public TUser getTUserById(int id){
        return mapper.getTUserById(id);
    }

    /**
     * 冻结
     */
    @Transactional
    public void freeze(int id, int state){
        mapper.freeze(id, state);
    }

    /**
     * 删除账户
     */
    @Transactional
    public void deleteUser(int id){
        mapper.deleteUser(id);
    }

    /**
     * 搜索用户
     */
    public List<TUser> searchUser(String key1, String key2){
        return  mapper.searchUser(key1, key2);
    }

    /**
     * 搜索动态
     */
    public List<VArticlePreInfo> searchArticle(String s, int itemNum){
        return mapper.searchArticle(s, itemNum);
    }

    /**
     * 删除动态
     */
    @Transactional
    public void deleteArticle(String uid){
        mapper.deleteArticle(uid);
    }

    /**
     * 获取话题分组
     */
    public List<TCommunity> getComList(){
        return mapper.getComList();
    }

    /**
     * 添加话题
     */
    @Transactional
    public boolean addTopic(TTopic tTopic, List<MultipartFile> files){
        if(mapper.hasTopicName(tTopic.getName()) > 0){
            return false;
        }
        MultipartFile image;
        if (files != null){
            if(files.size() > 0){
                image = files.get(0);
                try {
                    // 项目所在目录
                    String jar_parent  = new File(ResourceUtils.getURL("classpath:").getPath()).getParentFile().getParentFile().getParent();
                    jar_parent += File.separator+ ComPath.FILE_DIR +File.separator+ComPath.DEFAULT_IMG_PATH+File.separator;
                    String path = ComPath.FILE_DIR_SERVICE + File.separator + ComPath.DEFAULT_IMG_PATH + File.separator;
                    // 保存图片在本地
                    File image2 = new File(jar_parent + image.getOriginalFilename());
                    image.transferTo(image2);
                    // 添加文件名
                    tTopic.setTopicimg(image.getOriginalFilename());
                } catch (IOException e) {
                    e.printStackTrace();
                    //return false;
                }

            }
        }
        // 保存到数据库
        mapper.addTopic(tTopic);
        return true;
    }

    /**
     * 删除话题
     */
    @Transactional
    public void deleteTopic(String name){
        mapper.deleteTopic(name);
    }
}
